package com.jqr.activity.school.http;

import com.jqr.activity.school.models.jsontobean.JsonBean;
import com.jqr.activity.school.utils.ReflectionUtil;



import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.ObservableTransformer;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;

public class ResponseTransformer <T> implements ObservableTransformer<IResponse<T>,T>{

    private CompositeDisposable compositeDisposable;

    public  ResponseTransformer(CompositeDisposable compositeDisposable){
        this.compositeDisposable=compositeDisposable;
    }

    public ResponseTransformer(){

    }
    @Override
    public @NonNull ObservableSource<T> apply(@NonNull Observable<IResponse<T>> upstream) {
        return upstream
                .doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Throwable {
                if(compositeDisposable!=null){
                    compositeDisposable.add(disposable);
                }
            }
        })
                .onErrorResumeNext(new Function<Throwable, ObservableSource<? extends IResponse<T>>>() {
                    @Override
                    public ObservableSource<? extends IResponse<T>> apply(Throwable throwable) throws Throwable {
                        return Observable.error(ApiException.handleException(throwable));
                    }
                })
                .flatMap(new Function<IResponse<T>, ObservableSource<? extends T>>() {
                    @Override
                    public ObservableSource<? extends T> apply(IResponse<T> tiResponse) throws Throwable {
                      if(tiResponse.getSuccess()){
                          if(new JsonBean<T>().getData()!=null){
                              return Observable.just(new JsonBean<T>().getData().getData());
                          }
                          else {

                              Class<?> clz= ReflectionUtil.analysisClassInfo(tiResponse);
                              T obj=(T) clz.newInstance();

                              return Observable.just(obj);
                          }
                      }

                        return Observable.error(new ApiException(tiResponse.getCode(),tiResponse.getMsg()));
                    }
                });
    }

    public static  <U> ResponseTransformer<U> obtain(CompositeDisposable compositeDisposable){

        return  new ResponseTransformer<>(compositeDisposable);
    }

    public static  <U> ResponseTransformer<U> obtain(){

        return  new ResponseTransformer<>();
    }

}

